﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace FitAutomation.FitProcess
{
	public static class Serializer
	{
		static readonly Dictionary<Type, XmlSerializer> _serialziers = new Dictionary<Type, XmlSerializer>();
		static readonly Encoding _encoding = Encoding.UTF8;

		static XmlSerializer GetSerializer(Type type)
		{
			return GetSerializer(type, null);
		}

		static XmlSerializer GetSerializer(Type type, Type[] extraTypes)
		{
			XmlSerializer serializer;
			if (!_serialziers.TryGetValue(type, out serializer))
			{
				lock (_serialziers)
				{
					if (!_serialziers.TryGetValue(type, out serializer))
					{
						serializer = new XmlSerializer(type, extraTypes??new Type[0]);
						//_serialziers.Add(type, serializer);
					}
				}
			}
			return serializer;
		}

		public static Message SerializePackage(params object[] objs)
		{
			return Serialize(new XmlPackage(objs));
		}

		public static object[] DeserializePackage(Message buf)
		{
			return Deserialize<XmlPackage>(buf).Objects.ToArray();
		}

		public static Message Serialize(object obj)
		{
			var serializer = GetSerializer(obj.GetType());
			using (var ms = new MemoryStream())
			{
				serializer.Serialize(ms, obj);
				return ms.ToArray();
			}
		}

		public static T Deserialize<T>(Message buf)
		{
			return (T)Deserialize(buf, typeof(T));
		}

		public static object Deserialize(Message buf, Type type)
		{
			var serializer = GetSerializer(type);
			using (var ms = new MemoryStream(buf))
			{
				return serializer.Deserialize(ms);
			}
		}
	}
}
